#include "widget.h"
#include "ui_widget.h"

#include <QDebug>
#include <QTime>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->groupBoxTimer->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
    ui->groupBoxPrecise->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);

    m_timer = new QTimer(this);
    m_timer->stop();
    m_timer->setTimerType(Qt::CoarseTimer);
    ui->radioButtonCoarse->setChecked(true);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(do_timer_timeout()));
}

Widget::~Widget()
{
    if (ui) {
        delete ui;
        ui = nullptr;
    }
}

void Widget::do_timer_timeout()
{
    QApplication::beep();
    QTime curTime = QTime::currentTime();
    ui->lcdNumberHour->display(curTime.hour());
    ui->lcdNumberMin->display(curTime.minute());
    ui->lcdNumberSec->display(curTime.second());

    if (m_timer->isSingleShot()) {
        int tmMsec = m_counter.elapsed();
        QString str = QString("流逝的时间: %1 毫秒").arg(tmMsec);
        ui->labelElapsedTime->setText(str);

        ui->pushButtonStart->setEnabled(true);
        ui->pushButtonOneShot->setEnabled(true);
        ui->pushButtonStop->setEnabled(false);
    }
}

void Widget::do_timer_shot()
{
    QApplication::beep();
    int tmMsec = m_counter.elapsed();
    QString str = QString("流逝的时间: %1 毫秒").arg(tmMsec);
    ui->labelElapsedTime->setText(str);
    ui->pushButtonOneShot->setEnabled(true);
}

void Widget::on_pushButtonStart_clicked()
{
    m_timer->setInterval(ui->spinBoxIntv->value());

    if ( ui->radioButtonContiue->isChecked() ) {
        m_timer->setSingleShot(false);
    } else {
        m_timer->setSingleShot(true);
    }

    if ( ui->radioButtonPrecise->isChecked() ) {
        m_timer->setTimerType(Qt::PreciseTimer);
    } else if ( ui->radioButtonCoarse->isChecked() ) {
        m_timer->setTimerType(Qt::CoarseTimer);
    } else {
        m_timer->setTimerType(Qt::VeryCoarseTimer);
    }

    m_timer->start();
    m_counter.start();
    ui->pushButtonStart->setEnabled(false);
    ui->pushButtonOneShot->setEnabled(false);
    ui->pushButtonStop->setEnabled(true);
}

void Widget::on_pushButtonStop_clicked()
{
    m_timer->stop();

    int tmMsec = m_counter.elapsed();
    int ms = tmMsec % 1000;
    int sec = tmMsec/1000;

    QString str = QString("流逝的时间: %1 秒 %2 毫秒").arg(sec).arg(ms, 3, 10, QChar('0'));
    ui->labelElapsedTime->setText(str);

    ui->pushButtonStart->setEnabled(true);
    ui->pushButtonOneShot->setEnabled(true);
    ui->pushButtonStop->setEnabled(false);
}

void Widget::on_pushButtonOneShot_clicked()
{
    int intv = ui->spinBoxIntv->value();
    QTimer::singleShot(intv, Qt::PreciseTimer, this, &Widget::do_timer_shot);
    m_counter.start();
    ui->pushButtonOneShot->setEnabled(false);
}

